/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package medicalstorebilling.ui.tab2purchase;

import database.dao.MedicinesDao;
import database.dao.PurchasesDao;
import database.dao.StockDetailsDao;
import database.entity.Distributors;
import database.entity.Medicines;
import database.entity.Purchases;
import database.entity.StockDetails;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.swing.GroupLayout;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import medicalstorebilling.DatePicker;
import medicalstorebilling.ulti.DateConvert;
import medicalstorebilling.ulti.TimeStringConverter;

/**
 *
 * @author Administrator
 */
public class Phase2Purchase extends javax.swing.JPanel {

    /**
     * Creates new form Phase2Purchase
     */
    private Purchases purchase;
    private Phase1Purchase phase1;
    private GroupLayout prevlayout;
    private JPanel previous;
    private MedicinesDao medicineDao = new MedicinesDao();
    private Medicines med = new Medicines();
    private List<StockDetails> stockList = new ArrayList<StockDetails>();
    private Distributors distributor = new Distributors();

    public Distributors getDistributor() {
        return distributor;
    }

    public Medicines getMed() {
        return med;
    }

    public void setMed(Medicines med) {
        Medicines old = getMed();
        this.med = med;
        this.firePropertyChange("med", old, med);
        if (txtMedCode != null) {
            txtMedCode.setText(med.getCode());
            txtAvailStock.setText("<html><b>Available: " + med.getStock_not_expired_quantity() + "</b></html>");
        }
    }

    public void setDistributor(Distributors distributor) {
        Distributors old = getDistributor();
        this.distributor = distributor;
        this.firePropertyChange("distributor", old, distributor);
    }

    public List<StockDetails> getStockList() {
        return stockList;
    }

    public void setStockList(List<StockDetails> stockList) {
        List<StockDetails> old = getStockList();
        this.stockList = stockList;
        this.firePropertyChange("stockList", old, stockList);
        if (txtTotal != null) {
            updateTotal();
        }
    }

    /**
     * Get the value of purchase
     *
     * @return the value of purchase
     */
    public Purchases getPurchase() {
        return purchase;
    }

    /**
     * Set the value of purchase
     *
     * @param purchase new value of purchase
     */
    public void setPurchase(Purchases purchase) {
        Purchases old = getPurchase();
        this.purchase = purchase;
        this.firePropertyChange("purchase", old, purchase);
    }

    public Phase2Purchase(Purchases purchase) {
        setPurchase(purchase);
        initComponents();
    }

    public Phase2Purchase(Phase1Purchase phase1, GroupLayout layout, JPanel previous, Purchases purchase) {
        this.phase1 = phase1;
        this.prevlayout = layout;
        setPurchase(purchase);
        this.previous = previous;
        initComponents();
    }

    public Phase2Purchase() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jTextField5 = new javax.swing.JTextField();
        jTextField6 = new javax.swing.JTextField();
        jTextField7 = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jTextField8 = new javax.swing.JTextField();
        btnSelectDis = new javax.swing.JButton();
        txtPurchaseName = new javax.swing.JTextField();
        txtPurchaseTime = new javax.swing.JTextField();
        btnConfirm = new javax.swing.JButton();
        btnReset = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jpanelAddMed = new javax.swing.JPanel();
        jLabel9 = new javax.swing.JLabel();
        txtMedCode = new javax.swing.JTextField();
        btnAddMed = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        txtPurQuan = new javax.swing.JTextField();
        txtAvailStock = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtExpiredDate = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        txtPrice = new javax.swing.JTextField();
        btnDeleteMed = new javax.swing.JButton();
        txtTotal = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel12 = new javax.swing.JLabel();

        setPreferredSize(new java.awt.Dimension(800, 580));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Purchase Information"));
        jPanel1.setPreferredSize(new java.awt.Dimension(790, 170));

        jLabel1.setText("Name");

        jLabel2.setText("Time");

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Seller"));
        jPanel2.setPreferredSize(new java.awt.Dimension(450, 137));

        jLabel4.setText("Name");

        jLabel5.setText("Address");

        jLabel6.setText("Info");

        jLabel7.setText("Phone");

        jTextField4.setEditable(false);

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${distributor.description}"), jTextField4, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jTextField5.setEditable(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${distributor.address}"), jTextField5, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jTextField6.setEditable(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${distributor.name}"), jTextField6, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jTextField7.setEditable(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${distributor.phone}"), jTextField7, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jLabel8.setText("Type");

        jTextField8.setEditable(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${distributor.type}"), jTextField8, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        btnSelectDis.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/search.png"))); // NOI18N
        btnSelectDis.setText("SEARCH");
        btnSelectDis.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelectDisActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel6)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnSelectDis, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7)
                    .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSelectDis))
                .addContainerGap(19, Short.MAX_VALUE))
        );

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${purchase.name}"), txtPurchaseName, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        txtPurchaseTime.setEditable(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${purchase.time}"), txtPurchaseTime, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setConverter(new TimeStringConverter());
        bindingGroup.addBinding(binding);

        txtPurchaseTime.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtPurchaseTimeMouseClicked(evt);
            }
        });

        btnConfirm.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/ok.png"))); // NOI18N
        btnConfirm.setText("Confirm");
        btnConfirm.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConfirmActionPerformed(evt);
            }
        });

        btnReset.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/reset.png"))); // NOI18N
        btnReset.setText("Reset");
        btnReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResetActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnConfirm, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnReset, javax.swing.GroupLayout.DEFAULT_SIZE, 122, Short.MAX_VALUE))
                    .addComponent(txtPurchaseName)
                    .addComponent(txtPurchaseTime))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(17, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtPurchaseName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtPurchaseTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnConfirm)
                    .addComponent(btnReset))
                .addGap(24, 24, 24))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Purchase Details"));

        jScrollPane1.setPreferredSize(new java.awt.Dimension(760, 180));

        org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${stockList}");
        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, jTable1, "");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${medicine.code}"));
        columnBinding.setColumnName("Code");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${medicine.name}"));
        columnBinding.setColumnName("Medicine");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${expiredDate}"));
        columnBinding.setColumnName("Expired Date");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${boughtQuantity}"));
        columnBinding.setColumnName("Quantity");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${costPerUnit}"));
        columnBinding.setColumnName("Cost Per Unit");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${totalString}"));
        columnBinding.setColumnName("Total");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseExited(java.awt.event.MouseEvent evt) {
                jTable1MouseExited(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(3).setResizable(false);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(10);
        jTable1.getColumnModel().getColumn(4).setPreferredWidth(10);
        jTable1.getColumnModel().getColumn(5).setPreferredWidth(10);

        jpanelAddMed.setBorder(javax.swing.BorderFactory.createTitledBorder("Add Medicine"));
        jpanelAddMed.setPreferredSize(new java.awt.Dimension(770, 108));

        jLabel9.setText("Medicine Code");

        txtMedCode.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtMedCodeActionPerformed(evt);
            }
        });
        txtMedCode.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtMedCodeKeyTyped(evt);
            }
        });

        btnAddMed.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnAddMed.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/Add.png"))); // NOI18N
        btnAddMed.setText("Add");
        btnAddMed.setPreferredSize(new java.awt.Dimension(160, 23));
        btnAddMed.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddMedActionPerformed(evt);
            }
        });

        jButton6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/search.png"))); // NOI18N
        jButton6.setText("SEARCH");
        jButton6.setPreferredSize(new java.awt.Dimension(160, 23));
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jLabel10.setText("Quantity");

        txtAvailStock.setText("Availabe :");

        jLabel3.setText("Expired Date:");

        txtExpiredDate.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtExpiredDateMouseClicked(evt);
            }
        });

        jLabel11.setText("Price ($)");

        javax.swing.GroupLayout jpanelAddMedLayout = new javax.swing.GroupLayout(jpanelAddMed);
        jpanelAddMed.setLayout(jpanelAddMedLayout);
        jpanelAddMedLayout.setHorizontalGroup(
            jpanelAddMedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpanelAddMedLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpanelAddMedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAddMed, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45, Short.MAX_VALUE)
                .addGroup(jpanelAddMedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel9)
                    .addComponent(jLabel11))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpanelAddMedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jpanelAddMedLayout.createSequentialGroup()
                        .addComponent(txtPrice, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtAvailStock, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(txtMedCode, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(38, 38, 38)
                .addGroup(jpanelAddMedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel10))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpanelAddMedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(txtPurQuan, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtExpiredDate, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(52, 52, 52))
        );
        jpanelAddMedLayout.setVerticalGroup(
            jpanelAddMedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpanelAddMedLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpanelAddMedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9)
                    .addComponent(txtMedCode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(txtExpiredDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jpanelAddMedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAddMed, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11)
                    .addComponent(txtPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtAvailStock)
                    .addComponent(jLabel10)
                    .addComponent(txtPurQuan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnDeleteMed.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/Delete.png"))); // NOI18N
        btnDeleteMed.setText("Delete Selected");
        btnDeleteMed.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteMedActionPerformed(evt);
            }
        });
        btnDeleteMed.setEnabled(false);

        txtTotal.setText("<html><b>Total : </b></html>");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                                .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnDeleteMed))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addComponent(jpanelAddMed, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addComponent(jpanelAddMed, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnDeleteMed)
                    .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jButton1.setText("Exit");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel12.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel12.setText("PURCHASE INFORMATION");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(165, 165, 165)
                        .addComponent(jLabel12)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel12)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bindingGroup.bind();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAddMedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddMedActionPerformed
        // TODO add your handling code here:
        if (med == null) {
            JOptionPane.showMessageDialog(this, "Nothing to add", "Error", JOptionPane.ERROR_MESSAGE);
        } else {
            String error = "";
            int quantity = 0;
            Double price = 0.0;

            try {
                quantity = Integer.parseInt(txtPurQuan.getText());
            } catch (NumberFormatException e) {
                error += "Quantity must be a number\n";
            }
            if (quantity < 0) {
                error += "Quantity must be greater than 0\n";
            }
            Date expiredDate = DateConvert.convertDate(txtExpiredDate.getText());
            if (expiredDate == null) {
                error += "Date is not valid\n";
            } else if (expiredDate.before(new Date())) {
                error += "Expired date must be after today\n";
            }
            try {
                price = Double.parseDouble(txtPrice.getText().trim());
            } catch (NumberFormatException e) {
                error += "Price of medicine is not valid\n";
            }
            if (price <= 0) {
                error += "Price must be greater than 0\n";
            }
            if (!error.isEmpty()) {
                JOptionPane.showMessageDialog(this, error, "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            StockDetails stock = new StockDetails(0, med, purchase, quantity, BigDecimal.valueOf(price), expiredDate, quantity);
            List<StockDetails> list = new ArrayList<StockDetails>();
            for (Iterator<StockDetails> it = getStockList().iterator(); it.hasNext();) {
                StockDetails stockDetails = it.next();
                if (stockDetails.getMedicine().getCode().equals(stock.getMedicine().getCode())) {
                    if (stockDetails.getExpiredDate().equals(stock.getExpiredDate())) {
                        stock.setBoughtQuantity(stockDetails.getBoughtQuantity() + stock.getBoughtQuantity());
                        stock.setStockQuantity(stock.getBoughtQuantity());
                        it.remove();
                        break;
                    }
                }
            }
            list.addAll(getStockList());
            list.add(stock);
            setStockList(list);
        }
    }//GEN-LAST:event_btnAddMedActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:'
        this.phase1.refresh(evt);
        this.prevlayout.replace(this, previous);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void btnSelectDisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectDisActionPerformed
        // TODO add your handling code here:
        SelectorPopup selectDis = new SelectorPopup(null, true, distributor, this);
        selectDis.setVisible(true);
    }//GEN-LAST:event_btnSelectDisActionPerformed

    private void txtMedCodeKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtMedCodeKeyTyped
        // TODO add your handling code here:
        med = medicineDao.getByCode(txtMedCode.getText().trim());
        if (med != null) {
            txtAvailStock.setText("<html><b>Available: " + med.getStock_not_expired_quantity() + "</b></html>");
        } else {
            txtAvailStock.setText("<html><b>Available: N/A</b></html>");
        }
    }//GEN-LAST:event_txtMedCodeKeyTyped

    private void txtExpiredDateMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtExpiredDateMouseClicked
        // TODO add your handling code here:
        txtExpiredDate.setText(new DatePicker(null).setPickedDate());
    }//GEN-LAST:event_txtExpiredDateMouseClicked

    private void btnDeleteMedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteMedActionPerformed
        // TODO add your handling code here:
        if (jTable1.getSelectedRowCount() < 1) {
            JOptionPane.showMessageDialog(this, "Select at least one row to delete", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        List<StockDetails> list = new ArrayList<StockDetails>();
        for (int i : jTable1.getSelectedRows()) {
            list.add(getStockList().get(i));
        }
        List<StockDetails> tmp = new ArrayList<StockDetails>();
        for (StockDetails stockDetails : getStockList()) {
            if (list.contains(stockDetails)) {
                continue;
            } else {
                tmp.add(stockDetails);
            }
        }
        setStockList(tmp);
    }//GEN-LAST:event_btnDeleteMedActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        SelectorPopup selectDis = new SelectorPopup(null, true, med, this);
        selectDis.setVisible(true);
    }//GEN-LAST:event_jButton6ActionPerformed

    private void txtMedCodeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMedCodeActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtMedCodeActionPerformed

    private void jTable1MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseExited
        // TODO add your handling code here:
        if (jTable1.getSelectedRowCount() > 0) {
            btnDeleteMed.setEnabled(true);
        } else {
            btnDeleteMed.setEnabled(false);
        }
    }//GEN-LAST:event_jTable1MouseExited

    private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed
        // TODO add your handling code here:
        setDistributor(new Distributors());
        setStockList(new ArrayList<StockDetails>());
        txtPurchaseTime.setText("");
        txtPurchaseName.setText("");
    }//GEN-LAST:event_btnResetActionPerformed

    private void btnConfirmActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConfirmActionPerformed
        // TODO add your handling code here:
        String error = "";
        if (txtPurchaseName.getText().trim().isEmpty()) {
            error += "Purchase name cannot be empty\n";
        }
        if (txtPurchaseTime.getText().trim().isEmpty()) {
            error += "Purchase time cannot be empty\n";
        }
        if (getDistributor().getId() == 0) {
            error += "You have to select a distributor\n";
        }
        if (getStockList().isEmpty()) {
            error += "Your Purchase details cannot be empty\n";
        }
        if (!error.isEmpty()) {
            JOptionPane.showMessageDialog(this, error, "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        this.purchase.setName(txtPurchaseName.getText().trim());
        this.purchase.setDistributor(getDistributor());
        this.purchase.setTime(DateConvert.convertDate(txtPurchaseTime.getText().trim()));
        this.purchase.setStatus(0);
        this.purchase = new PurchasesDao().add(purchase);
        StockDetailsDao stDao = new StockDetailsDao();
        for (StockDetails stockDetails : stockList) {
            stockDetails.setPurchase(purchase);
            stDao.add(stockDetails);
        }
        JOptionPane.showMessageDialog(this, "New Purchase Created", "Success", JOptionPane.INFORMATION_MESSAGE);
        setUIforEdit();
    }//GEN-LAST:event_btnConfirmActionPerformed

    private void txtPurchaseTimeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtPurchaseTimeMouseClicked
        // TODO add your handling code here:
        if (this.purchase.getId()==0) {
            txtPurchaseTime.setText(new DatePicker(null).setPickedDate());
        }
    }//GEN-LAST:event_txtPurchaseTimeMouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddMed;
    private javax.swing.JButton btnConfirm;
    private javax.swing.JButton btnDeleteMed;
    private javax.swing.JButton btnReset;
    private javax.swing.JButton btnSelectDis;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton6;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    private javax.swing.JTextField jTextField7;
    private javax.swing.JTextField jTextField8;
    private javax.swing.JPanel jpanelAddMed;
    private javax.swing.JLabel txtAvailStock;
    private javax.swing.JTextField txtExpiredDate;
    private javax.swing.JTextField txtMedCode;
    private javax.swing.JTextField txtPrice;
    private javax.swing.JTextField txtPurQuan;
    private javax.swing.JTextField txtPurchaseName;
    private javax.swing.JTextField txtPurchaseTime;
    private javax.swing.JLabel txtTotal;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    public void setUIforEdit() {
        txtPurchaseName.setEditable(false);
        txtPurchaseTime.setEditable(false);
        jpanelAddMed.setVisible(false);
        btnReset.setVisible(false);
        btnConfirm.setVisible(false);
        btnSelectDis.setVisible(false);
        btnDeleteMed.setVisible(false);
    }

    public void setUIforNew() {
        btnDeleteMed.setVisible(true);
        txtPurchaseName.setEditable(true);
        jpanelAddMed.setVisible(true);
        btnReset.setVisible(true);
        btnConfirm.setVisible(true);
        btnSelectDis.setVisible(true);
    }

    private void updateTotal() {
        Double total = 0.0;
        for (StockDetails stockDetails : stockList) {
            total += stockDetails.getTotal();
        }
        txtTotal.setText("<html><b>Total: " + new DecimalFormat("'$' #,###,###.##").format(total) + "</b></html>");
    }
}
